<template>
  <div class="gisMap" :class="{ moveOrClick: moveOrClick }">
    <div id="container" :style="{ width: width, height: height }"></div>
    <!-- 控件 -->
    <component
      :is="'control'"
      :toolsShow="true"
      v-if="controlShow"
      :map="map"
      top="-460"
    ></component>

    <!-- 移动窗体 -->
    <moveInfo :name="name" ref="moveInfo"></moveInfo>
    <!-- 点击窗体（路线） -->
    <!-- <infoWindow v-model="item" ref="infoWindow"></infoWindow> -->
    <!-- 点击窗体（路网） -->
    <!-- <gridWindow v-model="item" ref="gridWindow"></gridWindow> -->
  </div>
</template>

<script>
var zoom = 13;
var opacity = 0.5;
export default {
  name: "gisMap",
  props: {
    width: {
      type: String,
      default: () => "1450px",
    },
    height: {
      type: String,
      default: () => "759px",
    },
    // 是否开启绘制线路
    isOpen: {
      type: Boolean,
      default: () => false,
    },
    isOpenGrid: {
      type: Boolean,
      default: () => false,
    },
    // 是否默认绘制路线
    defaultLines: {
      type: Array,
      default: () => [],
    },
    // 是否默认绘制路网
    defaultGrids: {
      type: Array,
      default: () => [],
    },
    // 是否开启路况（绘制颜色变化）
    isConditions: {
      type: Boolean,
      default: () => false,
    },
    // 是否开启路网颜色
    isGridsConditions: {
      type: Boolean,
      default: () => false,
    },
    // 是否绘制端点圆
    isCircle: {
      type: Boolean,
      default: () => true,
    },
    // 是否开启鼠标放入infoWindow(线)
    isMoveInfoWindow: {
      type: Boolean,
      default: () => false,
    },
    // 是否监听move移动事件(鼠标进入效果)
    isMoveLine: {
      type: Boolean,
      default: () => false,
    },
    // 是否可以点击线
    isClickLine: {
      type: Boolean,
      default: () => false,
    },
    // 是否可以点击网
    isClickGrid: {
      type: Boolean,
      default: () => false,
    },
    // 是否监听move移动事件(鼠标进入效果)
    isMoveGrid: {
      type: Boolean,
      default: () => false,
    },
    // 是否点击线显示infoWindow
    isClickInfoWindowLine: {
      type: Boolean,
      default: () => false,
    },
    // 是否显示label （主要绘制路网 绑定路线时使用）
    isShowLabel: {
      type: Boolean,
      default: () => false,
    },
    // 线透明度
    lineOpacity: {
      type: Number,
      default: () => 0.8,
    },
    // 路网透明度
    gridOpacity: {
      type: Number,
      default: () => 0.3,
    },
  },
  components: {
    control: () => import("@/components/skyMap/component/control"),
    moveInfo: () => import("./component/moveInfo"),
    infoWindow: () => import("./component/infoWindow"),
    gridWindow: () => import("./component/gridWindow"),
  },
  computed: {},
  data() {
    return {
      map: "",
      timer: "",
      editor: "",
      // 所有路线
      lines: [],
      // 绘制的路线
      addLines: [],
      // 所有路线一端圆点
      circles: [],
      // 绘制线路的端点
      addCircles: [],
      controlShow: false,
      // 移动窗体要的参数
      name: "",
      // 点击窗体要的参数
      item: {},
      // 移动窗体
      markerInfoWin: "",
      // 点击窗体
      clickInfoWin: "",
      // 所有网路
      grids: [],
      // 添加网路
      addGrids: [],
      moveOrClick: false,
    };
  },
  watch: {},
  mounted() {
    this.$nextTick(function () {
      this.initMap();
    });
  },

  methods: {
    // 开启绘制模式
    enableDraw(id) {
      // if (!this.editor) {
      var config = {
        showLabel: false,
        color: "blue",
        weight: 3,
        opacity,
        fillColor: "#FFFFFF",
        fillOpacity: this.gridOpacity,
      };
      switch (id) {
        case "polygon":
          this.editor = new T.PolygonTool(this.map, { ...config });
          break;
        case "circle":
          this.editor = new T.CircleTool(this.map, {
            follow: true,
            ...config,
          });
          break;
        case "rectangle":
          this.editor = new T.RectangleTool(this.map, {
            follow: true,
            ...config,
          });
          break;
        case "polyline":
          this.editor = new T.PolylineTool(this.map, {
            follow: true,
            color: "blue",
          });
          break;
      }
      // }
      // 打开绘制模式
      this.editor.open();

      // 监听事件
      this.editor.on("draw", (e) => {
        // 清除绘制工具绘制的图形
        this.editor.clear();
        switch (id) {
          case "polygon":
            var ids = Math.random();
            //创建网对象
            var gon = new T.Polygon(e.currentLnglats, {
              ...config,
            });
            //向地图上添加网
            this.map.addOverLay(gon);
            // 添加网(所有路网)
            var obj = {
              line: gon,
              id: ids,
              isCheck: false,
            };
            this.grids.push(obj);
            // 添加网(只有绘制的路网，用来判断是否可以新增)
            this.addGrids.push(obj);
            // 抛出添加的网
            this.$emit("setGrids", this.addGrids);
            break;
          case "polyline":
            var ids = Math.random();
            //创建线对象
            var line = new T.Polyline(e.currentLnglats, {
              color: "blue",
              opacity: this.lineOpacity,
            });
            //向地图上添加线
            this.map.addOverLay(line);
            // 添加线(所有路线)
            var obj = {
              line: line,
              id: ids,
              isCheck: false,
              trafficSituationColour: "blue",
            };
            this.lines.push(obj);
            // 添加线(只有绘制的路线，用来判断是否可以新增)
            this.addLines.push(obj);

            // 抛出添加的线
            this.$emit("setLine", this.addLines);

            // 绘制端点圆
            const defaultPois = {
              id: ids,
              lines: e.currentLnglats,
              color: "blue",
              trafficSituationColour: "blue",
              types: "draw",
            };
            if (this.isCircle) {
              this.setCircle(defaultPois, "add");
            }
            break;
          case "rectangle":
            // this.getSite(e.currentLnglats);
            var rt = e.currentBounds.Lq;
            var lb = e.currentBounds.kq;
            var lt = {
              lat: lb.lat,
              lng: rt.lng,
            };
            var rb = {
              lat: rt.lat,
              lng: lb.lng,
            };
            var geos = [rt, lt, lb, rb];
            break;
          default:
            // 圆
            console.log(e, "...e");
        }
      });
    },
    // 绑定事件
    addEventListener(obj, item, type = "", isMove, isClick) {
      // isMove 是否开启当前对象的move效果
      // isClick 是否开启当前对象的click效果
      var it = this.circles.find((it) => it.id == obj.id);
      // 是否具有移入效果
      if (isMove) {
        // 找到这条线段对应的圆(端点)
        // 鼠标进入
        obj.line.on("mouseover", (e) => {
          if (!obj.isCheck) {
            // 设置当前line样式
            obj.line.setColor(obj.line.getColor() || "blue");
            obj.line.setWeight(6);
            if (type !== "gon") {
              it.beforeCicle.setColor(obj.line.getColor() || "blue");
              it.beforeCicle.setWeight(10);
              it.endCircle.setColor(obj.line.getColor() || "blue");
              it.endCircle.setWeight(10);
            } else {
              obj.line.setFillColor(obj.line.getColor());
              obj.line.setFillOpacity(0.1);
            }
            // 如果开启infoWindow
            if (this.isMoveInfoWindow) {
              this.moveInfo(item, type);
            }
          }
        });
        // 鼠标离开(恢复默认样式)
        obj.line.on("mouseout", (e) => {
          if (!obj.isCheck) {
            // 清除其他line样式
            obj.line.setWeight(3);
            if (type !== "gon") {
              obj.line.setColor(obj.line.getColor() || "grey");
              it.beforeCicle.setColor(obj.line.getColor() || "grey");
              it.beforeCicle.setWeight(5);
              it.endCircle.setColor(obj.line.getColor() || "grey");
              it.endCircle.setWeight(5);
            } else {
              obj.line.setFillColor("#fff");
              obj.line.setFillOpacity(this.gridOpacity);
            }
            this.markerInfoWin.closeInfoWindow();
          }
        });
      }
      // 是否具有点击效果
      if (isClick) {
        obj.line.on("click", (e) => {
          //  取消移入事件
          if (type !== "gon") {
            // 清除其他样式
            this.setGreyLine();

            it.beforeCicle.setColor("blue");
            it.beforeCicle.setWeight(10);
            it.endCircle.setColor("blue");
            it.endCircle.setWeight(10);
            // 设置当前line样式
            obj.line.setColor("blue");
          } else {
            // 选中后其他设置网格为蓝色
            this.setDefaultGridsColor();
            // 设置当前grid样式
            obj.line.setColor("green");
            obj.line.setFillColor("green");
            obj.line.setFillOpacity(0.1);
          }
          this.$set(obj, "isCheck", true);
          obj.line.setWeight(6);
          // 如果开启infoWindow
          if (this.isClickInfoWindowLine) {
            this.item = {};
            this.$nextTick(function () {
              this.clickInfo(item, obj, type);
            });
          }
        });
      }
    },
    // 选中后其他设置为灰色
    setGreyLine() {
      this.lines.forEach((it) => {
        // 是否在开启点击时，禁用move
        this.$set(it, "isCheck", true);
        // 是否在开启点击时，不禁用move
        // this.$set(it, "isCheck", false);
        it.line.setColor("grey");
        it.line.setWeight(3);
      });
      this.circles.forEach((it) => {
        it.beforeCicle.setColor("grey");
        it.beforeCicle.setWeight(5);
        it.endCircle.setColor("grey");
        it.endCircle.setWeight(5);
      });
    },
    // 选中后其他设置网格为蓝色
    setDefaultGridsColor() {
      this.grids.forEach((it) => {
        // 是否在开启点击时，禁用move
        this.$set(it, "isCheck", true);
        // 是否在开启点击时，不禁用move
        // this.$set(it, "isCheck", false);
        it.line.setColor("blue");
        it.line.setFillColor("#fff");
        it.line.setFillOpacity(this.gridOpacity);
        it.line.setWeight(3);
      });
    },
    // 鼠标移入窗体
    moveInfo(item, type) {
      this.moveOrClick = false;
      this.name = item.roadNetworkName;
      this.markerInfoWin = new T.InfoWindow(this.$refs.moveInfo.$el, {
        minWidth: 72,
        autoPan: true,
        closeButton: false,
        closeOnClick: true,
      });
      var points = item?.lines?.[0] || item?.grids?.[0];
      // 创建信息窗口对象
      this.map.openInfoWindow(this.markerInfoWin, points);
    },
    clickInfo(item, obj, type) {
      this.moveOrClick = true;
      this.item = item;
      // var content =
      //   type == "gon" ? this.$refs.gridWindow.$el : this.$refs.infoWindow.$el;
      var content = this.$parent.$refs.infoWindow.$el;
      this.clickInfoWin = new T.InfoWindow(content, {
        minWidth: 350,
        autoPan: true,
      });
      var points = item?.lines?.[0] || item?.grids?.[0];
      // 创建信息窗口对象
      this.map.openInfoWindow(this.clickInfoWin, points);
      // 抛出方法
      this.$emit("setItem", item);
      //  如果关闭弹窗 所有设置为原本颜色
      this.clickInfoWin.on("clickclose", () => {
        // if (type == "gon") {
        //   this.setColorGrids();
        // } else {
        //   this.setColorLine();
        // }
        // 清除所有路网或者路线
        this.map.getOverlays().forEach((it) => {
          if (it?.ET?.className !== "infoWindow") {
            this.map.removeOverLay(it);
          }
        });
        // 清空数据
        this.circles = [];
        this.lines = [];
        // 重新绘制
        this.setDefaultLine();
        this.setDefaultGrids();
      });
    },
    // 设置为原本颜色
    setColorGrids() {
      this.lines.forEach((it) => {
        this.$set(it, "isCheck", false);
        it.line.setColor("blue");
        it.line.setFillColor("#fff");
        it.line.setFillOpacity(this.gridOpacity);
        it.line.setWeight(3);
      });
    },
    // 设置为原本颜色
    setColorLine() {
      this.lines.forEach((it) => {
        this.$set(it, "isCheck", false);
        it.line.setColor(it.trafficSituationColour);
        it.line.setWeight(3);
      });
      this.circles.forEach((it) => {
        it.beforeCicle.setColor(it.trafficSituationColour);
        it.beforeCicle.setWeight(5);
        it.endCircle.setColor(it.trafficSituationColour);
        it.endCircle.setWeight(5);
      });
    },
    // 销毁绘制模式
    disableDraw() {
      if (this.editor) {
        this.editor.close();
      }
      // 销毁'绘制'的图形
      this.addLines.forEach((it) => {
        this.map.removeOverLay(it.line);
      });
      // 销毁'绘制'的图形
      this.addCircles.forEach((it) => {
        this.map.removeOverLay(it.beforeCicle);
        this.map.removeOverLay(it.endCircle);
      });
      // 销毁'绘制'的图形
      this.addGrids.forEach((it) => {
        this.map.removeOverLay(it.line);
      });
      this.addLines = [];
      this.addCircles = [];
      this.addGrids = [];
    },
    // 设置默认路线(灰色或路况)
    setDefaultLine() {
      for (var i = 0; i < this.defaultLines.length; i++) {
        // 线条数
        var points = [];
        // 点数
        for (var j = 0; j < this.defaultLines?.[i].lines?.length; j++) {
          var lat = this.defaultLines?.[i].lines?.[j].lat;
          var lng = this.defaultLines?.[i].lines?.[j].lng;
          points = [...points, new T.LngLat(lng, lat)];
        }
        if (this.isConditions) {
          // 路况颜色
          var line = new T.Polyline(points, {
            color: this.defaultLines[i].trafficSituationColour || "grey",
            opacity: this.lineOpacity,
          });
        } else {
          // 默认颜色
          var line = new T.Polyline(points, {
            color: "grey",
            opacity: this.lineOpacity,
          });
        }
        // 绘制端点圆
        if (this.isCircle) {
          this.setCircle(this.defaultLines[i]);
        }
        //向地图上添加线
        this.map.addOverLay(line);

        var obj = { line: line, ...this.defaultLines[i], isCheck: false };
        // 添加线(所有路线)
        this.lines.push(obj);

        // 绑定移入或者点击事件
        this.addEventListener(
          obj,
          this.defaultLines[i],
          "",
          this.isMoveLine,
          this.isClickLine
        );

        // 是否开启展示label
        if (this.isShowLabel) {
          this.setLabel(obj);
        }
      }
    },
    // 设置默认路网(灰色或蓝色)
    setDefaultGrids() {
      var config = {
        showLabel: false,
        color: "blue",
        weight: 3,
        opacity,
        fillColor: "#FFFFFF",
        fillOpacity: this.gridOpacity,
      };
      for (var i = 0; i < this.defaultGrids.length; i++) {
        // 线条数
        var points = [];
        // 点数
        for (var j = 0; j < this.defaultGrids[i].grids.length; j++) {
          var lat = this.defaultGrids[i].grids[j].lat;
          var lng = this.defaultGrids[i].grids[j].lng;
          points = [...points, new T.LngLat(lng, lat)];
        }
        if (this.isGridsConditions) {
          // 路网颜色(开启路况使用路况颜色，没有就颜色 注：路网的路况颜色是‘前端自己遍历写死的’)
          // 后端没返回路网的路况颜色
          var gon = new T.Polygon(points, {
            ...config,
            color: this.defaultGrids[i]?.trafficSituationColour || config.color,
          });
        } else {
          // 默认颜色
          var gon = new T.Polygon(points, { ...config, color: "grey" });
        }
        //向地图上添加网
        this.map.addOverLay(gon);

        var obj = { line: gon, ...this.defaultGrids[i], isCheck: false };
        // 添加线(所有路线)
        this.grids.push(obj);

        // 绑定移入或者点击事件
        this.addEventListener(
          obj,
          this.defaultGrids[i],
          "gon",
          this.isMoveGrid,
          this.isClickGrid
        );
      }
    },
    // 绘制label
    setLabel(obj) {
      var label = new T.Label({
        text: obj.roadNetworkName,
        position: obj.lines[0],
        offset: new T.Point(-30, -20),
      });
      label.setBackgroundColor(obj?.trafficSituationColour || "#000");
      //创建地图文本对象
      this.map.addOverLay(label);
    },
    // 绘制端点圆
    setCircle(obj, type) {
      var len = obj.lines;
      // 结束点
      var endPoi = len[len.length - 1];
      var endCircle = new T.Circle(endPoi, {
        color:
          obj.types == "draw"
            ? obj.trafficSituationColour
            : this.isConditions
            ? obj?.trafficSituationColour || "grey"
            : "grey",
        weight: 5,
        fillOpacity: 1,
      });
      // 开始点
      var beforePoi = len[0];
      var beforeCicle = new T.Circle(beforePoi, {
        color:
          obj.types == "draw"
            ? obj.trafficSituationColour
            : this.isConditions
            ? obj?.trafficSituationColour || "grey"
            : "grey",
        weight: 5,
        fillOpacity: 1,
      });
      //向地图上添加线
      this.map.addOverLay(endCircle);
      //向地图上添加线
      this.map.addOverLay(beforeCicle);
      // 给数组添加圆
      this.circles.push({
        id: obj.id, // 此id为线条id  方便查询跟线相关的点
        endCircle,
        beforeCicle,
        ...obj,
      });
      // 单独给添加的圆push到数组
      if (type) {
        this.addCircles.push({
          id: obj.id, // 此id为线条id  方便查询跟线相关的点
          endCircle,
          beforeCicle,
          ...obj,
        });
      }
    },
    // 初始化地图
    initMap() {
      this.map = new T.Map("container", {
        projection: "EPSG:4326",
      });
      this.map.centerAndZoom(new T.LngLat(120.583618, 36.21163), zoom);
      this.controlShow = true;
      // 默认开启绘制(线绘制)
      if (this.isOpen) {
        this.enableDraw("polyline");
      }
      // 默认开启绘制(路网绘制)
      if (this.isOpenGrid) {
        this.enableDraw("polygon");
      }
      // 默认设置路线
      if (this.defaultLines.length) {
        this.setDefaultLine();
      }
      // 设置默认路网
      if (this.defaultGrids.length) {
        this.setDefaultGrids();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.gisMap ::v-deep {
  height: 100%;
  position: relative;
  &.moveOrClick {
    .tdt-infowindow-tip {
      background-color: #fff !important;
    }
  }
  // label
  .tdt-label {
    color: #ffffff;
    opacity: 0.7 !important;
  }
  // 窗体
  .tdt-infowindow {
    .tdt-infowindow-close-button {
      z-index: 99;
    }
    .tdt-infowindow-content-wrapper {
      padding: 0 !important;
      .tdt-infowindow-content {
        margin: 0 !important;
      }
    }
    .tdt-infowindow-tip {
      background-color: #000;
    }
  }
  // 筛选
  .sure {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .btns {
    display: flex;
    position: absolute;
    right: 150px;
    gap: 0 10px;
    top: 20px !important;
    z-index: 1000;
    .toolItem {
      width: 35px;
      height: 35px;
      float: left;
      margin: 1px;
      padding: 4px;
      border-radius: 3px;
      background-size: 100% 100%;
      background-position: center;
      background-repeat: no-repeat;
      box-shadow: 0 1px 2px 0 #e4e7ef;
      background-color: #ffffff;
      border: 1px solid #ffffff;
      &.active {
        border-color: #d5dff2;
        background-color: #d5dff2;
      }
    }
    .toolItem:hover {
      border-color: #789cff;
      cursor: pointer;
    }

    #polygon {
      background-image: url("https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polygon.png");
    }

    #circle {
      background-image: url("https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/circle.png");
    }

    #rectangle {
      background-image: url("https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/rectangle.png");
    }

    #ellipse {
      background-image: url("https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/ellipse.png");
    }

    #polyline {
      background-image: url("https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/polyline.png");
    }
  }
  .ivu-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 5px 0;
    .ivu-checkbox-wrapper {
      width: 50%;
      margin-right: 0;
    }
  }
}
</style>
